import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const createData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ id: Date.now(), value: '你好', count: 6 })
    }, 1500)
  })
}

export default new Vuex.Store({
  state: {
    // 需求：在登陆页面存储token; 在其他页面使用token.
    token: localStorage.getItem('token') || '',
    list: [
      { id: 1, value: 'hello Vue', count: 1 },
      { id: 2, value: 'hello react', count: 5 },
    ],
  },
  // 逻辑全部在mutation这个地方这个地方
  mutations: {
    set_token(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    set_list(state, item) {
      state.list.push(item)
    },
  },
  actions: {
    async getAsyncData({ commit }) {
      const data = await createData()
      commit('set_list', data)
    },
  },
  getters: {
    totalNum(state) {
      return state.list.reduce((num, item) => {
        return num + item.count
      }, 0)
    },
  },
  modules: {},
})
